from django.shortcuts import render
from django import http
from django.views import View
import logging
import json
import re
from django.contrib.auth import login, authenticate, logout
from meiduo_mall.utils.view import LoginRequiredJsonMixin


from django_redis import get_redis_connection
from apps.users.models import User, Address
from celery_tasks.email.tasks import send_verify_email
from apps.users.utils import verify_email_url, check_email_url

# Create your views here.

# 创建日志记录器
logger = logging.getLogger('django')


class ChangePasswordView(LoginRequiredJsonMixin, View):
    """ 修改密码
    PUT /password/
    """
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        old_password = json_dict.get('old_password')
        new_password = json_dict.get('new_password')
        new_password2 = json_dict.get('new_password2')

        if not all([old_password, new_password, new_password2]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必要参数'})

        # 这一步校验可以不用
        # if not re.match(r'^[a-zA-Z0-9]{8,20}$', old_password):
        #     return http.JsonResponse({'code': 400, 'errmsg': 'old_password参数格式有误'})

        # 验证密码
        if not request.user.check_password(old_password):
            return http.JsonResponse({'code': 400, 'errmsg': '输入密码不正确'})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', new_password):
            return http.JsonResponse({'code': 400, 'errmsg': 'new_password参数格式有误'})

        if new_password != new_password2:
            return http.JsonResponse({'code': 400, 'errmsg': 'new_password参数格式有误'})

        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '修改密码失败'})

        # 清除状态保持
        logout(request)

        response = http.JsonResponse({'code': 0, 'errmsg': '密码修改成功'})
        response.delete_cookie('username')
        return response


class UpdateTitleAddressView(View):
    """修改标题title
    PUT /addresses/7/title/
    """
    def put(self, request, address_id):
        # 提取参数
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        # 校验参数
        if not title:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必要参数'})

        try:
            address = Address.objects.get(id=address_id)
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '更改标题失败'})
        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class DefaultAddressView(LoginRequiredJsonMixin, View):
    """设置默认地址
    PUT /addresses/3/default/
    """
    def put(self, request, address_id):
        try:
            address = Address.objects.get(id=address_id)
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '设置默认地址失败'})

        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class UpdateDestroyAddressView(LoginRequiredJsonMixin, View):

    def put(self, request, address_id):
        """PUT
            /addresses/(?P<address_id>\d+)/
        """
        # 提取参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必要参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile参数格式有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400, 'errmsg': 'tel参数格式有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400, 'errmsg': 'email参数格式有误'})

        # 修改数据
        try:
            # 创建对象
            address = request.user.addresses.get(id=address_id)
            # 修改对象属性
            address.user_id = request.user.id
            address.province_id = province_id
            address.city_id = city_id
            address.district_id = district_id
            address.title = receiver
            address.receiver = receiver
            address.place = place
            address.mobile = mobile
            address.tel = tel
            address.email = email
            # 保存修改数据
            address.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '修改地址失败'})

        # 构造响应数据,没有这个修改页面,保存后无法跳出
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 返回响应
        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})

    def delete(self, request, address_id):
        """DELETE
        /addresses/(?P<address_id>\d+)/
        """
        try:
            address = request.user.addresses.get(id=address_id)
            # # 物理删除
            # address.delete()

            # 逻辑删除
            address.is_deleted = True
            address.save()

        except Exception as e:
            logger.error(e)
        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class AddressView(LoginRequiredJsonMixin, View):
    """获取收货地址
    GET /addresses/
    """
    def get(self, request):
        address_model_list = request.user.addresses.filter(is_deleted=False)
        address_list = []
        for address in address_model_list:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            # 把默认地址放到前面
            default_address = request.user.default_address
            if default_address == address.id:
                address_list.insert(0, address_dict)
            else:
                address_list.append(address_dict)

        default_address_id = request.user.default_address_id

        return http.JsonResponse({'code': 0, 'errmsg': 'ok',
                                  'default_address_id': default_address_id,
                                  'addresses': address_list})


class CreateAddressView(LoginRequiredJsonMixin, View):
    """新增地址
    POST /addresses/create/
    """
    def post(self, request):

        # 新增逻辑,判断新增地址的个数
        try:
            count = Address.objects.filter(user=request.user, is_deleted=False).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '获取地址数据失败'})
        if count >= 20:
            return http.JsonResponse({'code': 400, 'errmsg': '新增地址已满20个'})

        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必要的参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '手机格式有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400, 'errmsg': '手机格式有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400, 'errmsg': 'email格式有误'})

        # 保存新增地址
        try:
            address = Address.objects.create(
                user_id=request.user.id,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                title=receiver,
                receiver=receiver,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email,
            )
            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '新增地址失败'})

        # 这一步应该是不必要传的吧
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})
        # return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class VerifyEmailView(View):
    """邮箱验证状态
    PUT /emails/verification/
    """
    def put(self, request):
        # 提取参数
        token = request.GET.get('token')
        # 校验参数
        if not token:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少token'})
        # 反序列化，类似解密，返回用户对象
        user = check_email_url(token)
        if not user:
            return http.JsonResponse({'code': 400, 'errmsg': 'token验证连接无效'})

        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '邮件激活失败'})

        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class EmailView(LoginRequiredJsonMixin, View):
    """添加邮箱
    PUT /emails/
    """
    def put(self, request):
        """实现添加邮箱逻辑"""
        # 需要用到登录的用户对象对数据库进行修改，需要用到用户认证才行
        # 提取参数
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        # 校验参数
        if not email:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': 400, 'errmsg': 'email参数格式有误'})

        # 给数据库添加邮箱
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})

        # 发送验证邮件
        user = request.user
        verify_url = verify_email_url(user)
        send_verify_email.delay(email, verify_url)

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class UserInfoView(LoginRequiredJsonMixin, View):
    """用户中心
    GET /info/
    """
    def get(self, request):
        """实现显示用户中心的逻辑"""
        # 用户认证通过继承的父类进行判断
        # # request.user.is_authenticated用户登录为True,未登录为False
        # 这种判断用户是否登录的复用性不强，可以用django自带认证封装作为父类进行自定义
        # if not request.user.is_authenticated:
        #     return http.JsonResponse({'code': 400, 'errmsg': '用户未登录'})
        # print(request.GET.get('username'))  ---> None

        # 如果接口是用户认证才能访问的，接口内部可以直接使用request.user获取用户的信息，
        # request.user等价于某个用户信息的对象
        info_dict = {
            'code': 0,
            'errmsg': 'ok',
            'info_data': {
                'username': request.user.username,
                'mobile': request.user.mobile,
                'email': request.user.email,
                'email_active': request.user.email_active
            }
        }
        return http.JsonResponse(info_dict)


class LogoutView(View):
    """退出登录
    DELETE /logout/
    """
    def delete(self, request):
        """实现退出登录逻辑"""
        logout(request)

        response = http.JsonResponse({'code': 0, 'errmsg': '退出登录'})
        response.delete_cookie('username')
        return response


class LoginView(View):
    """实现登录
    POST  http://www.meiduo.site:8000/login/
    JSON 数据
    """
    def post(self, request):
        """实现用户登录逻辑"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        account = json_dict.get('username')
        password = json_dict.get('password')
        # 默认是False, 打钩就是True，选不选都无所谓，所以无需校验
        remembered = json_dict.get('remembered')

        # 校验参数
        if not all([account, password]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 实现多账户登录,根据认证authenticate最底层源代码来实现
        # 讲义使用重新定义类来实现，但是代码太多，以下最简单
        if re.match(r'^1[3-9]\d{9}$', account):
            User.USERNAME_FIELD = 'mobile'

        else:
            User.USERNAME_FIELD = 'username'

        # 为了减轻数据库压力，先过滤错误的输入
        # if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', account):
        #     return http.JsonResponse({'code': 400, 'errmsg': 'username格式错误'})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': 'password格式错误'})

        # 认证用户
        # 只是认证输入的用户是否是美多用户
        user = authenticate(username=account, password=password)

        if not user:
            return http.JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})

        # 状态保持
        login(request, user)

        response = http.JsonResponse({'code': 0, 'errmsg': '登录成功'})

        # 判断是否记住登录
        if remembered == True:
            # 选择记住登录，保存两周
            request.session.set_expiry(None)
            # 设置cookie，保存用户名--用于展示首页用户，保存两周
            response.set_cookie('username', user.username, max_age=14 * 24 * 3600)
        else:
            # 不选择记住登录，关闭就立刻失效
            request.session.set_expiry(0)
            # 设置cookie，保存用户名--用于展示首页用户，关闭就立刻失效
            response.set_cookie('username', user.username)

        # 下面注释的代码有瑕疵
        # # 设置cookie，保存用户名--用于展示首页用户
        # response = http.JsonResponse({'code': 0, 'errmsg': '登录成功'})
        # response.set_cookie('username', user.username, max_age=14*24*3600)

        # 响应结果
        return response


class RegisterView(View):
    """注册用户视图类
    POST http://www.meiduo.site:8000/register/
    """
    def post(self, request):
        """实现注册逻辑"""
        # 获取请求数据json，前后端分离，前端请求的数据是json数据
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        sms_code_client = json_dict.get('sms_code')
        allow = json_dict.get('allow')

        # 参数检验
        # all([]),列表里面的参数不为空即为True，参数有空即为False
        if not all([username, password, password2, mobile, sms_code_client, allow]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # r'^[a-zA-Z0-9_-]{5,20}$' 死死限定输入的最大字符长度20，最小为5，多出报错
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': 400, 'errmsg': 'username格式有误'})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': 'password格式有误'})

        if password2 != password:
            return http.JsonResponse({'code': 400, 'errmsg': '两次输入不对'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误'})

        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_code_%s' % mobile)

        if not sms_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})

        if sms_code_client != sms_code_server.decode():
            return http.JsonResponse({'code': 400, 'errmsg': '输入短信验证码有误'})

        if allow != True:
            return http.JsonResponse({'code': 400, 'errmsg': 'allow格式有误'})

        try:
            # 保存到数据库
            user = User.objects.create_user(username=username, password=password, mobile=mobile)

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '保存到数据库出错'})
        # 状态保持(登录)
        login(request, user)

        # 设置cookie，保存用户名--用于展示首页用户
        response = http.JsonResponse({'code': 0, 'errmsg': '注册成功'})
        # response.set_cookie('username', user.username, max_age=14 * 24 * 3600)  # 有瑕疵
        response.set_cookie('username', user.username)

        # 响应结果
        return response
        # return http.JsonResponse({'code': 0, 'errmsg': '注册成功'})


class UsernameCountView(View):
    """用户名重复查询视图类
    GET http://www.meiduo.site:8000/usernames/itcast/count/
    """
    def get(self, request, username):
        try:
            count = User.objects.filter(username=username).count()
            # print(count)
        except Exception as e:
            # 报错时把错误记录到日志中
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'count': count})


class MobileCountView(View):
    """手机重复查询视图
    GET http://www.meiduo.site:8000/mobiles/15962149852/count/
    """
    def get(self, request, phone_num):
        try:
            count = User.objects.filter(mobile=phone_num).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '访问失败'})

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'count': count})
